## -*- coding: utf-8 -*-
from cStringIO import StringIO
import urllib2
import uuid
from pdfminer.pdfinterp import PDFResourceManager, process_pdf
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from django.db import connection
from eVB1 import settings
from models import *
import re
import string
import random
import torndb
import json
import requests
import datetime

datetime_now = datetime.datetime.now

class VectorExt(object):
    """
    """
    def __init__(self, vector):
        """
        """
        self.vector = vector

    def get_discount(self):
        """
        """
        # todo: 返回相应载体的折扣
        result = 0.0

        return result

    @property
    def price(self):
        """
        载体价格

        :return:
        """
        if self.is_standard:
            result = 295  # 目前标准的
        else:
            result = 1000  #
        return round(result, 2)

    @property
    def tt(self):

        """
        载体周期


        :return:
        """
        if self.is_standard:
            result = '4 - 7'
        else:
            result = '30'  #

        return result

    @property
    def is_standard(self):

        """
        载体周期


        :return:
        """
        result = True

        return result


class CyagenApi(object):
    """
    """
    def __init__(self, **kwargs):
        """
        """
        self.prefix_url = 'http://api.cyagen.net'

    def get_shipping_cost(self, code2, zip_code='', category='ip'):
        """
        """
        result = 0.00
        url = '{prefix}/app/api/other/shipping_cost/?code2={code2}&zip_code={zip_code}&category={category}'.format(
            prefix=self.prefix_url, code2=code2, zip_code=zip_code, category=category
        )
        r = requests.get(url)
        if r.status_code == 200:
            result = float(r.json().get('result'))
        return result


def gen_info(type_, start, qty):
    """
    """
    result = []
    for i in range(0, random.randint(start, qty)):
        result.append({
            'slug': '{}{}'.format(type_, str(i).zfill(7)),
            'qty': random.randint(1, 10),
            'amount': round(random.uniform(200, 400), 2),
            'created_on': datetime_now
        })
    return result


def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for x in range(size))


def promotion_code_generator():
    """
    """
    result = '{}-{}-{}-{}'.format(id_generator(size=4), id_generator(size=4), id_generator(size=4), id_generator(size=4))
    
    return result

def month_range(year=None, month=None):
    """
    """
    import calendar
    from datetime import date

    if not year:
        year = date.today().year
    if not month:
        month = date.today().month
    first_tm = '%s-%s-%s 00:00:00' % (year, month, 1)
    last_tm = '%s-%s-%s 23:59:59' % (year, month, calendar.monthrange(year, month)[1])
    return first_tm, last_tm


def uriToID(str_uri):
    return re.sub(r'\/api\/v(\d+)\/(.*?)\/(\d+)\/?', r'\3', str_uri)


class dict2obj(object):
    """
    Convert dictionary to object
    @source http://stackoverflow.com/a/1305561/383912
    """

    def __init__(self, d):
        self.__dict__['d'] = d

    def __getattr__(self, key):
        value = self.__dict__['d'][key]
        if type(value) == type({}):
            return dict2obj(value)

        return value

# https://docs.djangoproject.com/en/dev/topics/db/sql/
def dictfetchall(cursor):
    "Returns all rows from a cursor as a dict"
    desc = cursor.description
    return [
        dict(zip([col[0] for col in desc], row))
        for row in cursor.fetchall()
    ]


def custom_sql(sql):
    cursor = connection.cursor()
    cursor.execute(sql)
    return dictfetchall(cursor)


def pdf_to_txt(pdf_path):
    input_ = file(pdf_path, 'rb')
    output = StringIO()

    manager = PDFResourceManager()
    converter = TextConverter(manager, output, laparams=LAParams())
    process_pdf(manager, converter, input_)

    return output.getvalue()


class Project(object):
    """
    """
    def __init__(self):
        """
        """
        self.base_url = 'http://project.cyagen.net'

    def get_list(self, term=None, _uuid=None, status='all', limit=20, offset=0):
        """
        """
        result = []
        meta = {'total_count': 2, 'limit': 1, 'offset': 0}
        for i in range(1, limit + 1):
            vectors = []
            for j in range(0, random.randint(1, 10)):
                vectors.append({
                    'id': j,
                    'vector_name': 'pAV.ExBi-{}'.format(id_generator()),
                    'uuid': uuid.uuid4(),
                    'progress': random.uniform(0, 1)
                })
            result.append({
                'id': i,
                'vectors': vectors,
                'slug': 'p1{}'.format(str(i).zfill(7)),
                'uuid': uuid.uuid4()
            })
        if _uuid and result:
            result = [result[0]]
        return result, meta

    def post(self, order_id):
        """
        """
        order = SalesOrder.objects.get(pk=order_id)
        #url = self.base_url + '/aaa/'
        url = "http://localhost:8002/api/v1/other/test/"
        data = {'order_id': order.id, 'vectors': []}
        for i in order.vector_set.all():
            data['vectors'].append({'uuid': i.uuid, 'gb_text': i.gb_text})
        headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
        result = requests.post(url, data=json.dumps(data), headers=headers)

        return json.loads(result.content)


class Requirement(object):
    """
    """
    def __init__(self):
        """
        """
        self.base_url = 'http://vb31.cyagen.net'

    def get_list(self, term=None, limit=20, offset=0):
        """
        """
        result = []
        meta = {'total_count': 2, 'limit': 1, 'offset': 0}
        for i in range(1, limit + 1):
            result.append({
                'id': i,
                'sender': uuid.uuid4(),
                'subject': 'pAV.ExBi-{}'.format(id_generator()),
                'slug': 'p1{}'.format(str(i).zfill(7))
            })
        return result, meta

    def get(self, uuid_):
        """
        """
        print uuid_
        result = {
            'id': 1,
            'uuid': uuid.uuid4(),
            'vector_name': 'pAV.ExBi-{}'.format(id_generator()),
            'slug': 'p1{}'.format(str(1).zfill(7))
        }
        return result



def get_method(params={}, username=settings.API_USERNAME, api_key=settings.API_KEY,
                  url=settings.VB_DOMAIN+'/api/v1/msg/evb_group_list/'):
    paramStr = ''
    if params:
        for key in params:
            if params.has_key(key):
                paramStr += '&'+str(key)+'='+str(params.get(key))
    url = url+'?username='+username+'&api_key='+api_key+paramStr
    response = urllib2.urlopen(url)
    con = response.read()
    # data = json.loads(con)
    # return data
    return con

def get_firstDatas(quote_num):
    firstDatas = []
    print 'quote_num model', quote_num
    params = {'quote_num': 'Q140323-10001'}
    getResult = json.loads(get_method(params=params, url=settings.VB_DOMAIN+'/api/v1/first-data/'))
    if getResult['meta']['total_count']:
        firstDatas = getResult['objects']
    return firstDatas